<style lang="scss" scoped>
.editAppo_dlg {
  /deep/ .el-dialog__body{
    padding: 0;
    /* height: 700px; */
  }
}
.editAppo_bg {
  /deep/ .el-dialog__body{
    padding: 0;
    display: flex;
  }
  /deep/ .check_container{
    width: 100%;
    background: #f0f0f0;
    padding-bottom: 0;
  }
  /deep/ .el-tree div{
    /* height: 400px; */
  }
}
iframe /deep/ .versionFlag{
    margin-top: -19px;
    display: block;
}

.checkIframe{
  width: 69%;
}
.appply_Check_box{
  position: relative;
}
/deep/ .el-checkbox {
  margin-right: 0px !important;
}
.popoverBox{
  z-index: 10001;
  background-color: #fff;
  color: #666;
  padding: 8px 10px;
  border-radius: 6px;
  border: 1px dotted #f0f0f0;
  position: relative;
  cursor: pointer;
}
// .closeBtn{
//   z-index: 10002;
//   position: absolute;
//   right: 0px;
//   top: -25px;
//   font-size: 24px;
//   color: #fff;
// }
.modal_mask{
  z-index: 10000;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
}
</style>
<template>
  <el-dialog
    :visible.sync="visible"
    top="50px"
    :width="isEditInfo ? '100%' : '1180px'"
    :close-on-click-modal="true"
    :destroy-on-close="true"
    :before-close="handleDicClose"
    :class="isEditInfo ? 'editAppo_bg' : 'editAppo_dlg'"
  >
    <template slot="title">
      <span class="titleText fs-18 font-bold">{{titleChange}}</span>
      <el-checkbox class="mar-l-20" v-show="titleChange === '改约'" v-permission="'YJYY10007001'" v-model="isJZ" @change="handleJZChange">急诊</el-checkbox>
      <el-checkbox class="mar-l-20" v-show="titleChange === '改约'" v-model="isVIP" label="VIP" @change="handleVIPChange">VIP</el-checkbox>
      <el-checkbox class="mar-l-20" v-show="fromCheckDepartment && titleChange === '改约'" v-model="fromChecked" label="强制预约" @change="handleChecked">强制预约</el-checkbox>
    </template>
    <!-- <div class="check_app_iframe_box"> -->
    <div class="appply_Check_box" v-if="isEditInfo">
      <ApplyCheck
        ref="applyCheck"
        style="height: calc(100vh - 160px)"
        @manual-registration="handleValueChanged"
        :dialog-visible-edit-appo="dialogVisibleEditAppo"
        @applyCheckEmit="applyCheckPostMsg"
        @editCheckInfo="editCheckInfoMsg"
        :hospital-code-form="hospitalCodeForm || hospitalCode"
        :hospital-name-form="hospitalNameForm || hospitalName"
        :is-edit-info.sync="isEditInfo"
        :from-appoint-type.sync="fromChecked"
        v-if="checkUrl && clinicalConfig"
      />
      <div style="bottom: 10px; right: 20px; position: absolute;">
        <!-- <el-button type="primary" size="mini" @click="modifyInfo()">查询</el-button> -->
        <div class="flex flex-row align-center">
          <div class="popoverBox flex flex-row align-center" @click="closePoperver" v-if="isShowMask">
            <!-- <i class="el-icon-circle-close" style="color: #999; font-size: 18px; margin-bottom: 1px;"></i> -->
            <span class="fs-14">登记信息若有修改，请重新点击→</span>
          </div>
          <el-button class="mar-l-10" style="padding: 8px 8px !important;z-index: 100020;" type="primary" @click="modifyInfo">号源查询</el-button>
        </div>
      </div>
      <div class="modal_mask" v-if="isShowMask" @click="closePoperver"></div>
    </div>
    <div class="check_app_iframe_box " :class="isEditInfo ? 'checkIframe' : ''">
      <CheckIframe
        ref="CheckIframe"
        v-if="checkUrl && clinicalConfig"
        :check-url="checkUrl"
        style="height: calc(100vh - 160px)"
        @iframePMBack="iframePMBack"
        :iframe-config="clinicalConfig"
      ></CheckIframe>
    </div>
  </el-dialog>
</template>

<script>
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import CheckIframe from '@/views/iframe/checkAppointment'
import { getAppointmentResultListByAccessno, getidgenerator, mobileJwtAccessTokenEncrypt, getSysHospitalGetModelByCode } from '@/api/api'
import ApplyCheck from '@/views/appointCenter/applyCheck'
import { dateFormatter } from '@/utils/validate'
// import { setIsClickAppoSearchPover } from '@/utils/auth'
import enc from '@/utils/aes'
import bus from '@/api/bus'
import { mapGetters } from 'vuex'
const CHECK_FORM_DEFAULT_KEY = 'CHECK_FORM_DEFAULT'
const CHECK_APPLY_FILE_KEY = 'CHECK_APPLY_FILE'
export default {
  components: {
    CheckIframe,
    ApplyCheck
  },
  props: {
    dialogVisibleEditAppo: {
      type: Boolean,
      default: false
    },
    isEditInfo: {
      type: Boolean,
      default: false
    },
    fromCheckDepartment: {
      type: Boolean,
      default: false
    },
    titleChange: {
      type: String,
      default: '改约'
    },
    hospitalCodeForm: {
      String,
      default: ''
    },
    hospitalNameForm: {
      String,
      default: ''
    }
  },
  data() {
    return {
      isShowMask: true,
      clientHeight: 860,
      isVIP: false,
      isJZ: false,
      userName: this.$store.state.user.userName,
      userCode: this.$store.state.user.userCode,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      token: null,
      pubcliKey: '',
      appoint_url: window.g.APPOINT_URL ? window.g.APPOINT_URL + '/index.html?isLogo=1' : '',
      appoint_type: window.g.APPOINT_TYPE || '前台登记',
      checkUrl: '',
      fromChecked: false,
      interNum: 0,
      changInfo: {},
      appointInfo: [],
      accessNo: '',
      checkType: '',
      checkUrlChange: null
    }
  },
  computed: {
    ...mapGetters(['gradeList']),
    clinicalConfig() {
      return this.$store.state.settings.clinicalContent
    },
    visible: {
      get() {
        return this.dialogVisibleEditAppo
      },
      set(val) {
        this.$emit('update:dialogVisibleEditAppo', val)
      }
    }
  },
  watch: {
    dialogVisibleEditAppo: function (val) {
      if (val) {
        this.fromChecked = false
      }
    }
  },
  created() {
    // setIsClickAppoSearchPover()
    console.log('this.$store.state', this.$store.state)
    const userPhone = this.$store.state.user.userInfo.userPhone
    const isClickAppoSearchPover = getLocalStorage(`isClickAppoSearchPover${userPhone}`)
    if (isClickAppoSearchPover == 1) {
      this.isShowMask = false
    } else {
      this.isShowMask = true
    }
    console.log('created=>editAppoDialog')
    this.clientHeight = document.body.clientHeight - 100
    const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY)
    if (checkFormDefault) {
      const cfd = JSON.parse(checkFormDefault)
      this.appoint_type = cfd.appoint_type
      // console.log('created=>缓存中的预约来源', this.appoint_type)
      this.areaName = cfd.areaName // 存的院区
    }
  },
  mounted() {
    // 对于优先级修改的监听
    bus.$off('changeGrade')
    bus.$on('changeGrade', (value) => {
      console.log('changeGrade=>', value)
      if (value === 'VIP') {
        this.isVIP = true
      } else {
        this.isVIP = false
      }
      if (value === '急诊') {
        this.isJZ = true
      } else {
        this.isJZ = false
      }
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
        type: 'patPriorityLevel',
        data: { grade: value }
      }, '*')
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy=>editAppoDialog')
    bus.$off('changeGrade')
    this.timeout01 && clearTimeout(this.timeout01)
    this.timeout02 && clearTimeout(this.timeout02)
  },
  methods: {
    closePoperver() {
      this.isShowMask = false
      const userPhone = this.$store.state.user.userInfo.userPhone
      console.log('userPhone', userPhone)
      setLocalStorage(`isClickAppoSearchPover${userPhone}`, 1)
    },
    async getidgenerator() {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCodeForm || this.hospitalCode
        }
        await getidgenerator(params).then(res => {
          if (res && res.code === 10000 && res.content) {
            const id = res.content
            resolve(id)
          }
          resolve(new Date().getTime())
        })
      })
    },
    modifyInfo() {
      this.$refs.applyCheck && this.$refs.applyCheck.setChangeInfo(this.checkType)
    },
    applyCheckPostMsg(data) {
      data.source = this.checkType === '1' ? data.source : 'editHisInfo'
      // console.log('applyCheckPostMsg_get_data', data)
      this.checkPostMsg(data)
      if (this.applyfile && data.patientId && this.applyCheckFileSHow) {
        // 附件上传，存存储本地，演示用
        let fileObj = getLocalStorage(CHECK_APPLY_FILE_KEY)
        fileObj = fileObj ? JSON.parse(fileObj) : {}
        fileObj[`${data.patientId}`] = this.applyfile
        setLocalStorage(CHECK_APPLY_FILE_KEY, JSON.stringify(fileObj))
      }
    },
    editCheckInfoMsg(data) {
      // console.error('applyCheckPostMsg')
      console.log('applyCheckPostMsg_get_data', data)
      this.checkPostMsg(data)
      if (this.applyfile && data.patientId && this.applyCheckFileSHow) {
        // 附件上传，存存储本地，演示用
        let fileObj = getLocalStorage(CHECK_APPLY_FILE_KEY)
        fileObj = fileObj ? JSON.parse(fileObj) : {}
        fileObj[`${data.patientId}`] = this.applyfile
        setLocalStorage(CHECK_APPLY_FILE_KEY, JSON.stringify(fileObj))
      }
    },
    async checkPostMsg(data) {
      console.log('=====checkPostMsg=====', data)
      data.token = await this.getToken(data.patientId)
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
    },
    handleValueChanged(value) {
      this.changInfo = {
        'source': 'editHisInfo',
        'data': value
      }
    },
    async init() {
      console.log('====init=====')
      this.checkUrl = ''
      this.checkUrlChange = setTimeout(() => {
        this.checkUrl = this.getCheckUrl()
      }, 0)
      await this.gethospitalInfo(this.hospitalCodeForm || this.hospitalCode)
    },
    handleJZChange(data) {
      // console.log('gradeList', this.gradeList)
      let value = ''
      if (data) {
        value = '急诊'
        this.isVIP = false
      } else {
        let findResult = -1
        findResult = this.gradeList.findIndex(item => item.item == '普通')
        // console.log('findResult', findResult)
        if (findResult > -1) {
          value = '普通'
        } else {
          findResult = this.gradeList.findIndex(item => item.item == '中')
          if (findResult > -1) {
            value = '中'
          } else {
            value = ''
          }
        }
      }
      // console.log('value', value)
      bus.$emit('JZChange', value)
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
        type: 'patPriorityLevel',
        data: { grade: value }
      }, '*')
    },
    handleVIPChange(data) {
      // console.log('gradeList', this.gradeList)
      let value = ''
      if (data) {
        value = 'VIP'
        this.isJZ = false
      } else {
        let findResult = -1
        findResult = this.gradeList.findIndex(item => item.item == '普通')
        // console.log('findResult', findResult)
        if (findResult > -1) {
          value = '普通'
        } else {
          findResult = this.gradeList.findIndex(item => item.item == '中')
          if (findResult > -1) {
            value = '中'
          } else {
            value = ''
          }
        }
      }
      // console.log('value', value)
      bus.$emit('VIPChange', value)
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
        type: 'patPriorityLevel',
        data: { grade: value }
      }, '*')
    },
    handleChecked(data) {
      if (data) {
        this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
          type: 'changeAppointmentTypeConfig',
          isNoRowCurr: this.rowCurr === '',
          data: { typeConfig: '检查科室' }
        }, '*')
      } else {
        this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
          type: 'changeAppointmentTypeConfig',
          isNoRowCurr: this.rowCurr === '',
          data: { typeConfig: this.appoint_type }
        }, '*')
      }
    },
    versionChange(type) {
      this.checkType = type
      if (window.g.jsonpRight) {
        if (!window.g.lcVERSION) {
          let newjs1 = window.sendJSONPRequest(window.g.APPOINT_URL + '/versionHandler.js', 'getLcVersion')
          newjs1.onload = () => {
            this.init()
          }
        } else {
          this.init()
        }
      } else {
        this.init()
      }
    },
    openRow(row, type) {
      const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY)
      // this.titleChange = this.checkType === '1' ? '绿检登记' : '改约'
      this.checkType = type
      this.versionChange(this.checkType)
      if (checkFormDefault) {
        const cfd = JSON.parse(checkFormDefault)
        this.appoint_type = cfd.appoint_type
        if (this.$hasPermission(['YJYY1000809781'])) {
          this.appoint_type = '临床预约'
        }
        if (this.$hasPermission(['YJYY1000809782'])) {
          this.appoint_type = '登记机房'
        }
        if (this.$hasPermission(['YJYY1000809783'])) {
          this.appoint_type = '检查科室'
        }
        if (this.$hasPermission(['YJYY1000809785'])) {
          this.appoint_type = '预约中心'
        }
        console.warn('this.appoint_type', this.appoint_type)
        this.areaName = cfd.areaName // 存的院区
      }
      // 弹窗左上角每增加以下快捷勾选框后，下面都要对应增加判断
      if (row[0].grade === 'VIP') {
        this.isVIP = true
      } else {
        this.isVIP = false
      }
      // console.log('isVIP', this.isVIP)
      if (row[0].grade === '急诊') {
        this.isJZ = true
      } else {
        this.isJZ = false
      }
      this.visible = true
      this.$refs.applyCheck && (this.$hasPermission(['YJYY10008040']) || this.$hasPermission(['YJYY10008052'])) ? this.$refs.applyCheck.isFresh() : null
      // this.isEditInfo = true
      this.$nextTick(() => {
        this.timeout01 = setTimeout(() => {
          this.appointmentPostMessage(row)
        }, 600)
      })
    },
    getCheckUrl() {
      let string = ''
      if (this.checkType === '1') {
        console.warn('string', string)
        string = this.appoint_url + `&v=${window.g.lcVERSION || window.g.VERSION}&yeFlag=1&hospitalCode=${this.hospitalCodeForm || this.hospitalCode}&hospitalName=${this.hospitalNameForm || this.hospitalName}&operateUser=${this.userName}&operateCode=${this.userCode}&patientId=`
      } else {
        string = this.appoint_url + `&v=${window.g.lcVERSION || window.g.VERSION}&yeFlag=1&yeRebookFlag=1&hospitalCode=${this.hospitalCodeForm || this.hospitalCode}&hospitalName=${this.hospitalNameForm || this.hospitalName}`
      // &operateUser=${this.userName}&operateCode=${this.userCode}&patientId=
      }
      return string
    },
    async appointmentPostMessage(row) {
      console.warn('appointmentPostMessage=>row', row)
      // 历史代码，最后取的还是this.checkType，这个判断有点多余（linqitai备注)
      this.checkType = row.type && row.type === '3' ? '2' : this.checkType
      console.warn('this.checkType', this.checkType)
      // this.titleChange = this.checkType === '1' ? '绿检登记' : '改约'
      // if (!this.pubcliKey) {
      //   this.$message.info('未配置医院公钥！')
      //   return
      // }
      if (!this.checkUrl) {
        this.$message.info('未配置预约地址！')
        return
      } else {
        if (row.length && row.length == 1) {
          const token = this.$store.getters.token
          const userInfo = this.$store.state.user.userInfo
          let resultByAccessno = []
          console.log('this.appoint_type===>', this.appoint_type)
          const choosePatient = {
            ApplyHospitalCode: row[0].hospitalCode,
            HospitalCode: row[0].hospitalCode,
            AccessNoList: row[0].accessionNo,
            isCheckDelete: !(this.checkType === '1')
          }
          getAppointmentResultListByAccessno(choosePatient).then(res => {
            // 处理返回的数据
            if (res && res.code === 10000) {
              let patientDetailInfo = JSON.parse(JSON.stringify(res.content.list))
              patientDetailInfo.type = this.checkType
              patientDetailInfo.row = row
              row.type === '3' ? null : bus.$emit('currentPatient', patientDetailInfo)
              this.appointInfo = res.content.list
              resultByAccessno = res.content.list
              this.accessNo = row[0].accessionNo
              const data = {
                type: row.type === '2' ? '2' : this.checkType, // 改签
                source: 'editHisInfo', // 改签
                applyHospitalCode: row[0].hospitalCode,
                hospitalCode: row[0].hospitalCode,
                appointmentType: this.appoint_type,
                accessNo: row[0].accessionNo,
                accessToken: `Bearer ${token}`,
                yijiToken: this.$store.getters.token,
                registerRoom: getLocalStorage('UserPermision') || '',
                // accessToken: `Bearer ${this.$store.getters.token}`,
                'depArea': row[0].depArea,
                'checkpos': row[0].checkpos,
                'scheduledModality': row[0].scheduledModality,
                'patId': row[0].patientId,
                'checkStatus': row[0].checkStatus,
                'operateUser': userInfo.userName,
                'operateCode': userInfo.userCode,
                'callRoom': row[0].callRoom,
                'appointmentDateBegin': dateFormatter(new Date()), // 取当前时间 2023-03-03
                'appointmentDateTime': this.getDateTime(row[0]), // 2023-03-03 13:30:00-14:00:00 (星期五)
                resultByAccessno: resultByAccessno,
                handSendMsg: row[0].handSendMsg
              }
              this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
            }
          }).catch(error => {
            // 处理错误
            this.loading = false
            console.error(error)
          })
          // bus.$emit('currentPatient', choosePatient)
        } else if (row.length && row.length > 1) {
          console.warn('row=>item', row)
          let isVIPAll = true
          let isJZAll = true
          row.forEach(item => {
            // console.log('row=>item', item)
            item.appointmentType = this.appoint_type
            if (item.grade != 'VIP') {
              isVIPAll = false
            }
            if (item.grade != '急诊') {
              isJZAll = false
            }
          })
          // console.log('isVIPAll', isVIPAll)
          // console.log('isJZAll', isJZAll)
          if (isVIPAll) {
            this.isVIP = true
          } else {
            this.isVIP = false
          }
          if (isJZAll) {
            this.isJZ = true
          } else {
            this.isJZ = false
          }
          this.isEditInfo = false
          let resultByAccessno = []
          this.accessNo = ''
          row.forEach(element => {
            // console.error('element', element)
            this.accessNo = this.accessNo + element.accessionNo + ','
          })
          console.log('我是批量改签')
          const choosePatient = {
            ApplyHospitalCode: row[0].hospitalCode,
            HospitalCode: row[0].hospitalCode,
            AccessNoList: this.accessNo.slice(0, -1)
          }
          const token = this.$store.getters.token
          const userInfo = this.$store.state.user.userInfo
          console.log('this.appoint_type===>', this.appoint_type)
          // const data = {
          //   type: '2', // 改签
          //   rebookList: row,
          //   accessToken: `Bearer ${token}`,
          //   'operateUser': userInfo.userName,
          //   'operateCode': userInfo.userCode,
          //   'appointmentDateBegin': dateFormatter(new Date()), // 取当前时间 2023-03-03
          //   'appointmentDateTime': this.getDateTime(row[0]) // 2023-03-03 13:30:00-14:00:00 (星期五)
          // }
          getAppointmentResultListByAccessno(choosePatient).then(res => {
            // 处理返回的数据
            if (res && res.code === 10000) {
              row.type === '3' ? null : bus.$emit('currentPatient', res.content.list)
              this.appointInfo = res.content.list
              resultByAccessno = res.content.list
              this.accessNo = row[0].accessionNo
              const data = {
                type: '2', // 改签
                source: 'editHisInfo', // 改签
                rebookList: row,
                registerRoom: getLocalStorage('UserPermision') || '',
                yijiToken: this.$store.getters.token,
                accessToken: `Bearer ${token}`,
                'operateUser': userInfo.userName,
                'operateCode': userInfo.userCode,
                'appointmentDateBegin': dateFormatter(new Date()), // 取当前时间 2023-03-03
                'appointmentDateTime': this.getDateTime(row[0]), // 2023-03-03 13:30:00-14:00:00 (星期五)
                resultByAccessno: resultByAccessno
              }
              this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
            }
          }).catch(error => {
            // 处理错误
            console.error(error)
          })
          // console.error('postMsg', data)
          // this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
        }
      }
    },
    flrStr(val) {
      return val === null ? '' : val
    },
    getDateTime(row) {
      if (row) {
        const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        const d = row.triggerDate.substring(0, 10)
        const bt = this.flrStr(row.beginTime) === '' ? '' : row.beginTime.substring(0, 5)
        const et = this.flrStr(row.endTime) === '' ? '' : row.endTime.substring(0, 5)
        const t = new Date(row.triggerDate).getDay()
        return `${d} ${bt}-${et} (${week[t]})`
      }
      return ''
    },
    getToken(patientId) {
      console.log('getToken', this.pubcliKey)
      return new Promise(async resolve => {
        const userInfo = this.$store.state.user.userInfo
        const data = {
          isRefreshToken: false,
          organizationCode: userInfo.hospitalCode,
          queryValue: patientId,
          operateUser: userInfo.userName,
          OperateCode: userInfo.userCode
        }
        const encData = enc.SM2Encrypt(JSON.stringify(data), this.pubcliKey)
        const params = {
          organizationCode: this.hospitalCodeForm || userInfo.hospitalCode,
          data: '04' + encData
        }
        let t = ''
        await mobileJwtAccessTokenEncrypt(params).then(res => {
          if (res && res.code === 10000) {
            t = res.content.accessToken
          }
        })
        resolve(t)
      })
    },
    gethospitalInfo(hospitalCode) {
      console.log('gethospitalInfo')
      return new Promise(async resolve => {
        await getSysHospitalGetModelByCode({ hospitalCode }).then(res => {
          console.log('gethospitalInfo=>res', res)
          this.pubcliKey = res.content.guomiKey
        })
        resolve()
      })
    },
    // async gethospitalInfo(hospitalCode) {
    //   console.log('gethospitalInfo')
    //   const result = await getSysHospitalGetModelByCode({ hospitalCode })
    //   console.log('result', result)
    // },
    handleDicClose() {
      this.visible = false
      this.checkUrlChange && clearTimeout(this.checkUrlChange)
      this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg({
        type: 'reload' // 改签
      }, '*')
      this.$emit('closeDialog')
    },
    iframePMBack(data) {
      // 改签成功回调
      // console.log('data=====>', data)
      if (data.type === 1) {
        this.$emit('changeAppo')
        this.timeout02 = setTimeout(() => {
          this.handleDicClose()
        }, 2000)
      }
    }
  }
}
</script>
